package com.cll.learn.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2020/10/9 17:09
 */
public class RequestIpUtil {

    private static final Logger logger = LoggerFactory.getLogger(RequestIpUtil.class);

    private static final String UNKNOWN = "unknown";

    private static final String LOCALHOST_IPV4 = "127.0.0.1";
    private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";

    private static final int expectIPLength = 15;

    /**
     * 解决了服务端和客户端在同一台机器上的问题，获取客户端和服务端的IP
     * @param request   请求
     * @return  获取到的客户端IP
     */
    public static String getIPAddress(HttpServletRequest request){
        char defaultSplitChar = ',';
        String clientIp = request.getHeader("x-forwarded-for");
        if(StringUtils.isEmpty(clientIp) || UNKNOWN.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if(StringUtils.isEmpty(clientIp) || UNKNOWN.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if(StringUtils.isEmpty(clientIp) || UNKNOWN.equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
            if(LOCALHOST_IPV4.equals(clientIp) || LOCALHOST_IPV6.equals(clientIp)){
                //根据网卡取本机配置的IP
                try {
                    clientIp = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    logger.error("******>>>>>> UnknownHostException" + e.getMessage(), e);
                    clientIp = "";
                } catch (Exception e) {
                    logger.error("******>>>>>> server internal error..." + e.getMessage(), e);
                    clientIp = "";
                }
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        // "***.***.***.***".length() = 15
        if(null != clientIp && clientIp.length() > expectIPLength){
            if(clientIp.indexOf(defaultSplitChar) > 0){
                clientIp = clientIp.substring(0, clientIp.indexOf(","));
            }
        }
        return clientIp;
    }
}
